package com.swpu.cbg.cnshop.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.squareup.okhttp.Response;
import com.swpu.cbg.cnshop.Constans;
import com.swpu.cbg.cnshop.R;
import com.swpu.cbg.cnshop.bean.User;
import com.swpu.cbg.cnshop.http.OkHttpHelper;
import com.swpu.cbg.cnshop.http.SpotsCallback;
import com.swpu.cbg.cnshop.msg.LoginResMsg;
import com.swpu.cbg.cnshop.utils.DESUtil;
import com.swpu.cbg.cnshop.utils.ManifestUtil;
import com.swpu.cbg.cnshop.utils.ToastUtil;
import com.swpu.cbg.cnshop.widget.ClearEditText;
import com.swpu.cbg.cnshop.widget.cnToolbar;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import cn.smssdk.gui.RegisterPage;
import cn.smssdk.utils.SMSLog;

/**
 * Created by chenboge on 16/2/18.
 */
public class RegisterActivity extends BaseActivity implements View.OnClickListener {

    private OkHttpHelper mHelper;

    private static final String DEFAULT_COUNTRY_ID = "42";

    private SMSEvenHanlder evenHanlder;

    @ViewInject(R.id.toolbar)
    private cnToolbar mToolbar;

    @ViewInject(R.id.edittxt_phone)
    private EditText PhoneText;

    @ViewInject(R.id.edittxt_pwd)
    private ClearEditText pwdText;

    @ViewInject(R.id.txtCountry)
    private TextView mCountryTetx;

    @ViewInject(R.id.txtCountryCode)
    private TextView mCountryCode;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_reg);
        ViewUtils.inject(this);
        initToolbar();
        SMSSDK.initSDK(this, ManifestUtil.getMetaDataValue(this, "mob_sms_appKey"),
                ManifestUtil.getMetaDataValue(this, "mob_sms_appSecrect"));

        evenHanlder = new SMSEvenHanlder();
        SMSSDK.registerEventHandler(evenHanlder);

        String[] country = SMSSDK.getCountry(DEFAULT_COUNTRY_ID);
        if (country != null) {

            mCountryCode.setText("+" + country[1]);

            mCountryTetx.setText(country[0]);

        }


    }


    private void initToolbar() {
        mToolbar.hideContent();
        mToolbar.showTitle();
        mToolbar.setEditButtonText("下一步");
        mToolbar.showEditButton();
        mToolbar.getmEditButton().setOnClickListener(this);
    }


    private void getCode() {

        String s=PhoneText.getText().toString()+mCountryTetx.getText().toString()+ pwdText.getText().toString();

        String phone = PhoneText.getText().toString().trim().replaceAll("\\s*", "");
        String code = mCountryCode.getText().toString().trim();
        String pwd = pwdText.getText().toString().trim();

        checkPhoneNum(phone, code);

        //not 86   +86

        //验证成功就会回调callback接口
        SMSSDK.getVerificationCode(code, phone);

    }


    private void checkPhoneNum(String phone, String code) {
        if (code.startsWith("+")) {
            code = code.substring(1);
        }

        if (TextUtils.isEmpty(phone)) {
            ToastUtil.showToast(this, "请输入手机号码");
            return;
        }

        if (code == "86") {
            if (phone.length() != 11) {
                ToastUtil.showToast(this, "手机号码长度不对");
                return;
            }

        }

        String rule = "^1(3|5|7|8|4)\\d{9}";
        Pattern p = Pattern.compile(rule);
        Matcher m = p.matcher(phone);

        if (!m.matches()) {
            ToastUtil.showToast(this, "您输入的手机号码格式不正确");
            return;
        }

    }


    @Override
    public void onClick(View v) {
        getCode();
    }


    class SMSEvenHanlder extends EventHandler {


        @Override
        public void afterEvent(final int event, final int result,
                               final Object data) {


            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    //回调完成
                    if (result == SMSSDK.RESULT_COMPLETE) {
                        if (event == SMSSDK.EVENT_GET_SUPPORTED_COUNTRIES) {
                            //返回支持发送验证码的国家列表
                            onCountryListGot((ArrayList<HashMap<String, Object>>) data);

                        } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                            // 请求验证码后，跳转到验证码填写页面
                            afterVerificationCodeRequested((Boolean) data);

                        } else if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                            //提交验证码成功
                        }
                    } else {
                        // 根据服务器返回的网络错误，给toast提示
                        try {
                            ((Throwable) data).printStackTrace();
                            Throwable throwable = (Throwable) data;

                            JSONObject object = new JSONObject(
                                    throwable.getMessage());
                            String des = object.optString("detail");
                            if (!TextUtils.isEmpty(des)) {
                                ToastUtil.showToast(RegisterActivity.this, des);
                                return;
                            }
                        } catch (Exception e) {
                            SMSLog.getInstance().w(e);
                        }

                    }


                }
            });
        }
    }


    private void onCountryListGot(ArrayList<HashMap<String, Object>> countries) {
        // 解析国家列表
        for (HashMap<String, Object> country : countries) {
            String code = (String) country.get("zone");
            String rule = (String) country.get("rule");
            if (TextUtils.isEmpty(code) || TextUtils.isEmpty(rule)) {
                continue;
            }
            Log.d("tag", "code=" + code + "rule=" + rule);
        }

    }

    private String[] getCurrentCountry() {
        String mcc = getMCC();
        String[] country = null;
        if (!TextUtils.isEmpty(mcc)) {
            country = SMSSDK.getCountryByMCC(mcc);
        }

        if (country == null) {
            Log.w("SMSSDK", "no country found by MCC: " + mcc);
            country = SMSSDK.getCountry(DEFAULT_COUNTRY_ID);
        }
        return country;
    }

    private String getMCC() {
        TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        // 返回当前手机注册的网络运营商所在国家的MCC+MNC. 如果没注册到网络就为空.
        String networkOperator = tm.getNetworkOperator();
        if (!TextUtils.isEmpty(networkOperator)) {
            return networkOperator;
        }

        // 返回SIM卡运营商所在国家的MCC+MNC. 5位或6位. 如果没有SIM卡返回空
        return tm.getSimOperator();
    }


    /**
     * 请求验证码后，跳转到验证码填写页面
     */
    private void afterVerificationCodeRequested(boolean smart) {

        String phone = PhoneText.getText().toString().trim().replaceAll("\\s*", "");
        String code = mCountryCode.getText().toString().trim();
        String pwd = pwdText.getText().toString().trim();

        if (code.startsWith("+")) {
            code = code.substring(1);
        }
        Intent intent = new Intent(RegisterActivity.this, RegisterScendActivity.class);
        intent.putExtra(Constans.BaseUserInf.PHONE, phone);
        intent.putExtra(Constans.BaseUserInf.PASSWORD, pwd);
        intent.putExtra(Constans.BaseUserInf.COUNTRYCODE, code);
        startActivity(intent);


        ToastUtil.showToast(this,"发送验证码成功");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        SMSSDK.unregisterEventHandler(evenHanlder);

    }

}
